package com.fishery.memo.service.Impl;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishery.entity.GlobalException;
import com.fishery.entity.Result;
import com.fishery.entity.StatusCode;
import com.fishery.memo.client.UserClient;
import com.fishery.memo.entity.Task;
import com.fishery.memo.entity.client.User;
import com.fishery.memo.mapper.TaskMapper;
import com.fishery.memo.service.TaskService;
import com.fishery.memo.util.MessageManager;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private MessageManager messageManager;

    @Override
    public boolean createTask(Task task) {
        task.setId(null);
        task.setStatus(1);

        QueryWrapper<Task> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", task.getUserId());
        Integer count = taskMapper.selectCount(wrapper);
        if (count > 10) {
            throw new GlobalException(StatusCode.ERROR, "每个用户只能设置十个定时任务");
        }

        boolean retValue = taskMapper.insert(task) > 0;

        if (retValue) {
            try {
                messageManager.registerMessage(task);
            } catch (Exception e) {
                throw new GlobalException(StatusCode.ERROR, e.getMessage());
            }
        }
        return retValue;
    }

    @Override
    public boolean updateTask(Task task) {
        Task originTask = taskMapper.selectById(task.getId());
        if (originTask == null){
            throw new GlobalException(StatusCode.ERROR,"定时任务不存在");
        }
        if (!originTask.getUserId().equals(task.getUserId())){
            throw new GlobalException(StatusCode.ERROR,"用户id无法修改");
        }
        if (task.getTaskContent() == null || task.getTaskContent().isEmpty()){
            throw new GlobalException(StatusCode.ERROR,"定时任务内容不能为空");
        }
        boolean result = taskMapper.updateById(task) > 0;
        if (result){
            try {
                messageManager.removeTask(task.getId());
                messageManager.registerMessage(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public boolean deleteTask(String taskId) {
        boolean result = taskMapper.deleteById(taskId) > 0;
        if (result){
            try {
                messageManager.removeTask(taskId);
            } catch (Exception e) {
                throw new GlobalException(StatusCode.ERROR,e.getMessage());
            }
        }
        return result;
    }

    @Override
    public boolean pauseTask(String taskId) {
        UpdateWrapper<Task> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",taskId).set("status",0);
        boolean result = taskMapper.update(new Task(),wrapper) > 0;
        if (result){
            try {
                messageManager.pauseTask(taskId);
            } catch (Exception e) {
                throw new GlobalException(StatusCode.ERROR,e.getMessage());
            }
        }
        return result;
    }

    @Override
    public boolean resumeTask(String taskId) {
        UpdateWrapper<Task> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",taskId).set("status",1);
        boolean result = taskMapper.update(new Task(),wrapper) > 0;
        if (result){
            try {
                messageManager.resumeTask(taskId);
            } catch (Exception e) {
                throw new GlobalException(StatusCode.ERROR,e.getMessage());
            }
        }
        return result;
    }

    @Override
    public List<Task> searchTask(String userId) {
        Map<String,Object> map = new HashMap<>(1,1);
        map.put("user_id",userId);
        return taskMapper.selectByMap(map);
    }

    @Override
    public IPage<Task> searchTask(String userId, Integer page, Integer size) {
        QueryWrapper<Task> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        Page<Task> taskPage = new Page<>(page,size);
        return taskMapper.selectPage(taskPage, wrapper);
    }

    @Override
    public List<Task> searchRunningTask() {
        HashMap<String, Object> map = new HashMap<>(1,1);
        map.put("status",1);
        return taskMapper.selectByMap(map);
    }

    @Override
    public Task searchTaskById(String taskId) {
        return taskMapper.selectById(taskId);
    }
}
